
package net.starwifi.duobao.service.impl;


import net.starwifi.duobao.entity.Operator;
import net.starwifi.duobao.entity.Role;
import net.starwifi.duobao.oauth.Principal;
import net.starwifi.duobao.repository.OperatorRepository;
import net.starwifi.duobao.service.BaseServiceImpl;
import net.starwifi.duobao.service.OperatorService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class OperatorServiceImpl extends BaseServiceImpl<Operator,Long> implements OperatorService {

    @Autowired
    OperatorRepository repository;

    @Override
    public Operator findByUsername(String username) {
        return repository.findByUsername(username);
    }


    @Override
    public Boolean usernameExists(String username) {
        Operator operator=repository.findByUsername(username);
        if(operator!=null){
            return true;
        }else return false;
    }

    @Transactional(readOnly = true)
    public Operator getCurrent() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            Principal principal = (Principal) subject.getPrincipal();
            if (principal != null) {
                return find(principal.getId());
            }
        }
        return null;
    }

    @Transactional(readOnly = true)
    public List<String> findAuthorities(Long id) {
        List<String> authorities = new ArrayList<String>();
        Operator operator = find(id);
        if (operator != null) {
            for (Role role : operator.getRoles()) {
                authorities.addAll(role.getAuthorities());
            }
        }
        return authorities;
    }
}
